package com.jbit.dm_160.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class RedisUtils {
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    public void set(String key,Object value){
        String json = JSON.toJSONString(value,SerializerFeature.WriteClassName);
        redisTemplate.opsForValue().set(key,json);
    }

    /**
     *
     * @param key
     * @param value
     * @param expire 过期时间
     */
    public void set(String key,Object value,Long expire){
        String json = JSON.toJSONString(value, SerializerFeature.WriteClassName);
        redisTemplate.opsForValue().set(key,json,expire, TimeUnit.MILLISECONDS);
    }

    public Object getObject(String key,Class clazz){
        String json = redisTemplate.opsForValue().get(key);
        //将json转换成指定类型
        return JSON.parseObject(json,clazz);
    }

    public <T> T get(String key){
        System.out.println("打印:");
        System.out.println(redisTemplate.opsForValue().get(key));
        String json = redisTemplate.opsForValue().get(key);
        return (T) JSON.parseObject(json);
    }

    /**
     * 删除key
     * @param key
     * @return
     */
    public boolean delete(String key){
        return redisTemplate.delete(key);
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean exists(String key){
        return redisTemplate.hasKey(key);
    }
}
